package com.zsl.controller;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "GetUserName", urlPatterns = "/getUsername")
public class GetUserName extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String name = (String) session.getAttribute("user");
        String date = (String) session.getAttribute("loginTime");
        ServletContext servletContext = request.getServletContext();
        //获取
        Integer count = (Integer) servletContext.getAttribute("count");
        //获取application
        List<String> onlineList = (List<String>) request.getServletContext().getAttribute("allUser");
        Map<String, Object> res = new HashMap<>();
        if (name == null || name.equals("")) {
            res.put("code", 0);
        } else {
            res.put("code", 1);
            res.put("name", name);
            res.put("lastLogin", date);
            res.put("counts", count);
            res.put("onlineList",onlineList.toString());
        }
        PrintWriter out = response.getWriter();
        out.write(JSON.toJSONString(res));
    }
}
